// Copyright (c) 2013 Inkling Systems, Inc. All rights reserved.
package com.inkling.imagesearch;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

public class SearchTask extends AsyncTask<String, Void, Void> implements OnItemClickListener {
	
	 private ProgressDialog dialog;
	
	 private Handler handler;
	 
	 private ArrayList<Object> listImages;
	 
	 private int msg;
	 private int page;
	 
	 //constructor
	 public SearchTask(Handler h, ArrayList<Object> data, int page ){
		 handler = h;
		 listImages = data;
		 this.page = page;
	 }
	 @Override
	 protected void onPreExecute() {
        super.onPreExecute();

     }

	@Override
	protected Void doInBackground(String... keywords) {
	   for(int i=0; i<2; i++){
		try {
			// TODO: Loads data appropriately with error handling
			
			// Google Image Search API
			// See https://developers.google.com/image-search/v1/jsondevguide for details
			URL url;
			int result=0, index=0;
			//set start of index and number of result
			if(i==0){ 
				result=8;
				index = page - 14;
			}
			if(i==1){ 
				result=7;
				index =page - 6;
			}
			Log.d("h2", "index::" + index);
			url = new URL("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=" + result + "&start=" + index + "&q=" + keywords[0]);
			
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();			
			InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
			InputStreamReader reader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(reader);
			StringBuilder stringBuilder = new StringBuilder();

			String line = null;
		    while ((line = bufferedReader.readLine()) != null) {
		        stringBuilder.append(line + "\n");
		    }

		    // Here we obtain various parts of the response
		    JSONObject responseJSON = new JSONObject(stringBuilder.toString());		    
		    JSONObject responseData = responseJSON.getJSONObject("responseData");
		    
		    JSONArray results = responseData.getJSONArray("results");
		    
		    this.populateImageList(results);

		    Log.v("SearchTask", "Number of images received: " + results.length());
	
		    
			urlConnection.disconnect();				

			// TODO: Pass the result out of this method
			// (may require giving SearchTask a proper Result type when extending AsyncTask)
			
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("h2", "error in searchTask");	
			//send error message
			msg = -1;
			return null;
		}
		msg = 1;
	 }
	return null;
	  
	}

	@Override
    protected void onPostExecute(Void result) {
		// TODO: Pass the data back to the owner of the task
		handler.sendEmptyMessage(msg);
		
    }
	
	public ArrayList<Object> populateImageList(JSONArray resultArray)
	{
		   ImageProperty imageProperty;
			try 
			{
				for(int i=0; i<resultArray.length(); i++)
				{
					JSONObject obj;
					obj = resultArray.getJSONObject(i);
					imageProperty = new ImageProperty();
				   
					imageProperty.setThumbUrl(obj.getString("tbUrl"));
				
					listImages.add(imageProperty);		   
				} 
				
			 }
			 catch (JSONException e) 
			 {	e.printStackTrace(); }
	return listImages;		 
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
}
